//
//  HDFFoodObject.m
//  Food
//
//  Created by 包月兴 on 2018/7/26.
//  Copyright © 2018年 包月兴. All rights reserved.
//

#import "HDFFoodObject.h"
#import "RLMObject+Extension.h"
#import <BmobSDK/Bmob.h>
#import "HDBmobFramework.h"

@implementation HDFFoodObject
+(NSString *)primaryKey
{
    return @"objectId";
}

+(NSArray<NSString *> *)ignoredProperties
{
    return @[@"buyCount"];
}

+(NSArray<NSString *> *)indexedProperties
{
    return @[@"priority",@"updatedAt"];
}



+(void)insertDataWithBmobObjectLists:(NSArray<BmobObject *> *)lists complete:(void (^)(NSError * _Nullable))complete
{
    __block NSMutableArray *arr = [NSMutableArray array];
    [lists enumerateObjectsUsingBlock:^(BmobObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HDFFoodObject *foodObject =[[HDFFoodObject alloc] initWithBmobObject:obj];
        [arr addObject:foodObject];
    }];
    if (arr.count > 0) {
        [self mainAsynDataBlock:^{
            RLMRealm *realm = [RLMRealm defaultRealm];
            NSError *error;
            [realm transactionWithBlock:^{
                [realm addOrUpdateObjects:arr];
            } error:&error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(error);
                }
            });
        }];
        return;
    }
    if (complete) {
        complete(nil);
    }
}

+(RLMResults *)listOrderByAscendingWithPriorityWithCategoryId:(NSString *)categoryId
{
    NSString *where = [NSString stringWithFormat:@"categoryId = '%@'",categoryId];
    return [HDFFoodObject objectsWhere:where];
}

+(NSDate *)getNewUpdatedAt
{
    RLMResults *results =[[HDFFoodObject allObjects] sortedResultsUsingKeyPath:@"updatedAt" ascending:YES];
    if (results.count > 0) {
        HDFFoodObject *object = results.lastObject;
        return object.updatedAt;
    }else
    {
        return nil;
    }
}


-(instancetype)initWithBmobObject:(BmobObject *)object
{
    if (self = [super init]) {
        _objectId = [object objectForKey:@"objectId"];
        _name = [object objectForKey:@"title"];
        _updatedAt = [BmobDataInstance.formatter dateFromString: [object objectForKey:@"updatedAt"]];
        _priority =  [[object objectForKey:@"priority"] integerValue];
        _price = [[object objectForKey:@"price"] doubleValue];
        _imgUrl = [object objectForKey:@"thumb_url"];
        BmobObject *category = [object objectForKey:@"category"];
        _categoryId = category.objectId;
        
    }
    return self;
}
@end
